//
//  JKBrowserViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/2.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import WebKit

class JKBrowserViewController: JKBaseViewController {
    
    var request: URLRequest?

    /** 背景 */
    @IBOutlet weak var bgToolBar: UIToolbar!
    
    /** 底部工具条 */
    @IBOutlet weak var bottomToolBar: UIToolbar!
    
    @IBOutlet weak var bottomToolBarBottomCons: NSLayoutConstraint!
    
    /** 返回 */
    @IBOutlet weak var backItem: UIBarButtonItem!
    
    /** 刷新 */
    @IBOutlet weak var refreshItem: UIBarButtonItem!
    
    /** 上一页 */
    @IBOutlet weak var preItem: UIBarButtonItem!
    
    /** 下一页 */
    @IBOutlet weak var forwardItem: UIBarButtonItem!
    
    /** 分享 */
    @IBOutlet weak var shareItem: UIBarButtonItem!
    
    /** indicatorView */
    private lazy var indicatorView: UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: indicatorView)
        
        return indicatorView
    }()
    
    /** 夜间模式遮盖view */
    private lazy var coverView: UIView = {
        
        let coverView = UIView()
        
        coverView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        coverView.isUserInteractionEnabled = false
        coverView.isHidden = true
        view.addSubview(coverView)
        
        return coverView
    }()
    
    /** webView */
    private lazy var webView: WKWebView = {
        
        // 解决内存泄露问题
        let config = WKWebViewConfiguration()
        config.selectionGranularity = WKSelectionGranularity.character
        
        // 让网页内容自适应大小
        let jScript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); ('meta[name=description]').remove(); ('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );"
        let wkUScript = WKUserScript(source: jScript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        
        let wkUController = WKUserContentController()
        wkUController.addUserScript(wkUScript)
        //        [wkUController addScriptMessageHandler:self name:@"openInfo"]
        config.userContentController = wkUController
        
        // 创建WKWebView
        let webView = WKWebView(frame: JKScreenBounds, configuration: config)
        //        webView.isOpaque = false
//        webView.scrollView.jk_adapt_iOS_11_scrollView()
        webView.backgroundColor = UIColor.clear
        webView.scrollView.backgroundColor = UIColor.clear
        webView.navigationDelegate = self
        webView.scrollView.delegate = self
        //        if ([webView respondsToSelector:@selector(setAllowsLinkPreview:)]) {
        //            webView.allowsLinkPreview = YES
        //        }
        //        webView.scrollView.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:nil refreshingAction:nil]
        contentView.insertSubview(webView, at: 0)
        
        return webView
    }()
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    // MARK: - 初始化
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        automaticallyAdjustsScrollViewInsets = false
        
        coverView.frame = CGRectMake(0, 0, JKScreenW, JKScreenH - self.bottomToolBarBottomCons.constant)
        
        navTitle = "跳转中..."
        
        bottomToolBarBottomCons.constant = JKCurrentHomeIndicatorHeight
        
        if let _ = request {
            
            webView.load(request!)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        webView.frame = CGRect(x: 0, y: JKNavBarHeight, width: view.bounds.size.width, height: view.size.height - JKNavBarHeight - bottomToolBar.frame.size.height - bottomToolBarBottomCons.constant)
    }

    @IBAction func backItemClick(_ sender: Any) {
        
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func refreshItemClick(_ sender: Any) {
        
        webView.reload()
    }
    
    @IBAction func preItemClick(_ sender: Any) {
        
        webView.goBack()
    }
    
    @IBAction func forwardItemClick(_ sender: Any) {
        
        webView.goForward()
    }
    
    @IBAction func shareItemClick(_ sender: Any) {
        
        let url = self.webView.url?.absoluteString
        
        JKShareView.showWithShareUrl(url: url, title: webView.title)
    }
    
    deinit {
        
        webView.scrollView.delegate = nil
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


// MARK: - webView代理

extension JKBrowserViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
        indicatorView.startAnimating()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        indicatorView.stopAnimating()
        
        navigationItem.title = webView.title
        
        preItem.isEnabled = webView.canGoBack
        forwardItem.isEnabled = webView.canGoForward
        
        getImageUrlsViaJs()
        
        // 禁止捏合手势
        //let javascript = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
        //webView.evaluateJavaScript(javascript, completionHandler: nil)
    }
    
    // 这里是js，主要目的实现对url的获取
    private func getImageUrlsViaJs() {
        
        webView.evaluateJavaScript("function registerImageClickAction(){var imgs=document.getElementsByTagName('img');var length=imgs.length;for(var i=0;i<length;i++){img=imgs[i];  img.onclick=function(){window.location.href='image-preview:'+this.src }}}", completionHandler: nil)
        webView.evaluateJavaScript("registerImageClickAction();", completionHandler: nil)
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
        indicatorView.stopAnimating()
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        guard let url = navigationAction.request.url else {
            
            decisionHandler(WKNavigationActionPolicy.allow)
            
            return
        }
        
        if url.scheme == "image-preview" {
            
            let path = url.absoluteString.substring(from: "image-preview:".count).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            
            JKImageBrowserView.showWith(imageUrlStr: path)
            
            decisionHandler(WKNavigationActionPolicy.cancel)
            
        }else {
            
            decisionHandler(WKNavigationActionPolicy.allow)
        }
    }
}

extension JKBrowserViewController {
    
    override func updateSkin() {
        
        if vcSkinModel == currentSkinModel {
            return
        }
        
        super.updateSkin()
        
        coverView.isHidden = (currentSkinModel == JKDaySkinModelValue)
    }
}
